package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.driver.config.QiniuProperties;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.qiniu.storage.Configuration;

import java.io.InputStream;
import java.util.UUID;


@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

    @Resource
    private QiniuProperties qiniuProperties;


    @Override
    public CosUploadVo upload(MultipartFile file, String path) {
        //判断文件类型
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();

        //如果判断通过上传文件到OSS
        String uploadPath = "driver/" + path + "/" + UUID.randomUUID().toString().replace("-", "") + originalFilename;
        String url = uploadOss(file, uploadPath);
        CosUploadVo cosUploadVo = new CosUploadVo();
        cosUploadVo.setUrl(uploadPath);
        cosUploadVo.setShowUrl(url);
        return cosUploadVo;

    }


    private String uploadOss(MultipartFile imgFile, String path) {
        String accessKey = qiniuProperties.getAccessKey();
        String secretKey = qiniuProperties.getSecretKey();
        String bucket = qiniuProperties.getBucket();

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = path;
        try {
            InputStream inputStream = imgFile.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(inputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                return qiniuProperties.getUrlPrefix() + key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore 
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return qiniuProperties.getUrlPrefix();
    }
}
